<template>
  <el-row :gutter="20" class="app-container">
    <Splitpanes>
      <pane size="16" v-if="$auth.hasRoleOr(['admin','manager','fishingceo'])">
        <el-col>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>
      <pane :size="$auth.hasRoleOr(['admin','manager','fishingceo']) ? 84 : 100">

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['pond:pond:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['pond:pond:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['pond:pond:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['pond:pond:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="pondList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键ID" align="center" prop="id" />
          <el-table-column label="鱼塘名称" align="center" prop="name" />
          <el-table-column label="是否回鱼" align="center" prop="isReturnFish">
            <template #default="scope">
              {{ scope.row.isReturnFish == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column label="价格段" align="center" width="200">
            <template #default="scope">
              <div v-if="scope.row.priceSegments && scope.row.priceSegments.length > 0">
                  <el-tag type="success" size="small" v-for="(segment, index) in scope.row.priceSegments" :key="index" class="price-segment-display">
                    {{ segment.price }}元/{{ segment.durationHours }}小时<span v-if="segment.returnPrice">【回鱼：{{segment.returnPrice}}元/斤】</span>
                  </el-tag>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            label="存鱼量/斤"
            align="center"
            prop="actualWeight"
          />
           <el-table-column
            label="备注"
            align="center"
            prop="remark"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['pond:pond:edit']"
                >修改</el-button
              >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['pond:pond:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改鱼塘管理对话框 -->
        <el-dialog :title="title" v-model="open" width="80%" append-to-body>
          <el-form
            ref="pondRef"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="鱼塘名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入鱼塘名称" />
            </el-form-item>
            <el-form-item label="所属钓场" prop="deptId">
              <DeptSelect
                v-model="form.deptId"
                @change="handleDeptChange"
              />
            </el-form-item>
            <el-form-item label="是否回鱼" prop="isReturnFish">
              <el-select v-model="form.isReturnFish">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="价格段" prop="priceSegments">
              <div
                v-for="(segment, index) in form.priceSegments"
                :key="index"
                class="price-segment"
              >
                <el-row gutter="10">
                  <el-col :span="8">
                    <el-form-item
                      label="价格(元)"
                      :prop="'priceSegments.' + index + '.price'"
                      label-width="80px"
                    >
                      <el-input
                        v-model.number="segment.price"
                        placeholder="请输入价格"
                        type="number"
                        :min="0"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="时长(小时)"
                      :prop="'priceSegments.' + index + '.durationHours'"
                      label-width="80px"
                    >
                      <el-input
                        v-model.number="segment.durationHours"
                        placeholder="请输入时长"
                        type="number"
                        :min="0"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="form.isReturnFish === 1">
                    <el-form-item
                      label="回鱼：元/斤"
                      :prop="'priceSegments.' + index + '.returnPrice'"
                      label-width="90px"
                    >
                      <el-input
                        v-model.number="segment.returnPrice"
                        placeholder="请输入回鱼金额"
                        type="number"
                        :min="0"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="form.isReturnFish === 1 ? 2 : 8" style="display: flex; justify-content: center; align-items: flex-end;">
                    <el-button
                      type="danger"
                      icon="Delete"
                      size="small"
                      @click="removePriceSegment(index)"
                      v-if="form.priceSegments.length > 1"
                      style="margin-top: 32px;"
                    ></el-button>
                  </el-col>
                </el-row>
              </div>
              <el-button type="primary" icon="Plus" @click="addPriceSegment"
                >添加价格段</el-button
              >
            </el-form-item>
            <el-form-item label="原塘鱼重量">
              <el-input
                v-model.number="form.currentWeight"
                placeholder="请输入原塘鱼重量"
              />
            </el-form-item>
             <el-form-item label="鱼种" prop="fishTypes">
              <el-select
                v-model="form.fishTypes"
                multiple
                placeholder="请选择鱼种"
                style="width: 100%"
              >
                <el-option
                  v-for="fish in fishTypeOptions"
                  :key="fish.fishId"
                  :label="fish.fishName"
                  :value="Number(fish.fishId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>

      </pane>
    </Splitpanes>
  </el-row>
</template>

<script setup name="Pond">
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { useDeptTree } from "@/utils/deptTreeUtils";
import DeptSelect from "@/components/DeptSelect/index.vue";

import { getCurrentInstance, watch } from "vue";
const { proxy } = getCurrentInstance();
import {
  listPond,
  getPond,
  delPond,
  addPond,
  updatePond
} from "@/api/pond/pond";
import { fishOptions } from "@/api/pond/fishtype";
const pondList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const fishTypeOptions = ref([]);

// 使用部门树工具
const {
  deptOptions,
  enabledDeptOptions,
  getDeptTree,
  handleFormDeptNodeClick,
  handleSidebarDeptNodeClick,
} = useDeptTree();

// 创建默认价格段
function createDefaultPriceSegment() {
  return {
    price: null,
    durationHours: null,
    returnPrice: null,
  };
}

const data = reactive({
  form: {
    priceSegments: [createDefaultPriceSegment()],
    fishTypes: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
  },
  rules: {
    name: [{ required: true, message: "鱼塘名称不能为空", trigger: "blur" }],
    deptId: [{ required: true, message: "所属钓场不能为空", trigger: "blur" }],
    priceSegments: [
      { required: true, message: "价格段不能为空", trigger: "change" },
      { validator: validatePriceSegments, trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 监听是否回鱼字段变化，清空回鱼金额
watch(() => form.value.isReturnFish, (newVal) => {
  if (newVal === 0) {
    // 当设置为不回鱼时，清空所有价格段的回鱼金额
    form.value.priceSegments.forEach(segment => {
      segment.returnPrice = null;
    });
  }
});


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 表单中的部门树节点点击事件 */
function handleFormDeptNodeClickLocal(data, node, e) {
  handleFormDeptNodeClick(data, node, e, (deptId) => {
    form.value.deptId = deptId;
  }, proxy, 'deptTreeSelectRef');
}

/** 侧边栏部门树节点单击事件 */
function handleNodeClick(data) {
  handleSidebarDeptNodeClick(data, (deptId) => {
    queryParams.value.deptId = deptId;
    handleQuery();
  });
}

/** 查询鱼塘管理列表 */
function getList() {
  loading.value = true;
  listPond(queryParams.value).then((response) => {
    pondList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    isReturnFish: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    price: null,
    currentWeight: null,
    actualWeight: null,
    durationHours: null,
    priceSegments: [createDefaultPriceSegment()],
    fishTypes: [],
  };
  proxy.resetForm("pondRef");
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef && proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加鱼塘管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPond(_id).then((response) => {
    form.value = response.data;
    // 确保fishTypes是数组格式，处理后端返回的数据
    if (form.value.fishTypes && Array.isArray(form.value.fishTypes)) {
      // 后端返回的是字符串数组，需要转换为数字以匹配el-select的value
      form.value.fishTypes = form.value.fishTypes.map(id => Number(id));
    } else if (!form.value.fishTypes) {
      form.value.fishTypes = [];
    }
    open.value = true;
    title.value = "修改鱼塘管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pondRef"].validate((valid) => {
    if (valid) {
      // 处理鱼种数据格式，确保传递给后端的是字符串数组
      const submitData = {
        ...form.value,
        fishTypes: form.value.fishTypes.map(id => String(id))
      };
      
      if (form.value.id != null) {
        updatePond(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPond(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除鱼塘管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPond(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "pond/pond/export",
    {
      ...queryParams.value,
    },
    `pond_${new Date().getTime()}.xlsx`
  );
}

/** 添加价格段 */
function addPriceSegment() {
  form.value.priceSegments.push(createDefaultPriceSegment());
}

/** 删除价格段 */
function removePriceSegment(index) {
  form.value.priceSegments.splice(index, 1);
}

/** 验证价格段 */
function validatePriceSegments(rule, value, callback) {
  if (!value || value.length === 0) {
    callback(new Error('价格段不能为空'));
    return;
  }
  
  for (let i = 0; i < value.length; i++) {
    const segment = value[i];
    
    // 检查必填字段
    if (!segment.price || !segment.durationHours) {
      callback(new Error(`第${i + 1}个价格段信息不完整`));
      return;
    }
    
    // 检查价格和时长是否为正数
    if (segment.price <= 0) {
      callback(new Error(`第${i + 1}个价格段：价格必须大于0`));
      return;
    }
    
    if (segment.durationHours <= 0) {
      callback(new Error(`第${i + 1}个价格段：时长必须大于0`));
      return;
    }
  }
  
  callback();
}

/** 部门选择变化事件 */
function handleDeptChange(deptId) {
  // 当部门改变时，可以在这里添加相关逻辑
  console.log('选择的部门ID:', deptId);
}

/** 获取鱼种选项 */
function getFishTypeOptions() {
  fishOptions().then((response) => {
    fishTypeOptions.value = response.rows || [];
  });
}

getDeptTree();
getList();
getFishTypeOptions();
</script>

<style scoped>
.price-segment {
  width: 100%;
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fafafa;
}

.price-segment .el-form-item {
  margin-bottom: 0;
}

.price-segment .el-row {
  align-items: flex-end;
}

.price-segment-display {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
